<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">事务管理</el-breadcrumb-item>
      <el-breadcrumb-item>所有事务</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="searchForm" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="searchForm.name" placeholder="请输入姓名或号码"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-date-picker
          size = "small"
          v-model="searchForm.date"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00']">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-download" @click="downloadFile">全部导出</el-button>
        <el-button size="small" type="primary" icon="el-icon-download" @click="downloadFiles">批量导出</el-button>
        <el-button size="small" type="danger" icon="el-icon-delete" @click="deletePres">批量删除</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="tableData" :row-key="getRowsKeys" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;font-size: 15px" ref="multipleTable" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" :reserve-selection="true" width="50">
      </el-table-column>
      <el-table-column  sortable prop="id" label="ID" width="60">
      </el-table-column>
<!--      <el-table-column prop="number" label="号码" width="75">-->
<!--      </el-table-column>-->
      <el-table-column prop="name" label="姓名" width="90">
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="120">
      </el-table-column>
      <el-table-column sortable prop="sex" label="性别" width="80">
      </el-table-column>
      <el-table-column sortable prop="age" label="年龄" width="80">
      </el-table-column>
      <el-table-column sortable prop="appointmentDate" label="预约日期" width="110">
        <template slot-scope="scope">
          <div>{{scope.row.appointmentDate|spliceDate}}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="appointmentPeriodId" label="预约时间段" width="120">
        <template slot-scope="scope" v-if="scope.row.appointmentPeriodId != null">
          <div>
            <span v-if="scope.row.appointmentPeriodId === 99">-</span>
            <span v-else>{{checkAppointmentPeriod(scope.row.appointmentPeriodId)}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="registrationTime" label="挂号时间" width="150">
        <template slot-scope="scope" v-if="scope.row.registrationTime != null">
          <div>{{scope.row.registrationTime|spliceDate2}}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="visitingTime" label="就诊时间" width="150">
        <template slot-scope="scope" v-if="scope.row.visitingTime != null">
          <div>{{scope.row.visitingTime|spliceDate2}}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="completionTime" label="完成时间" width="150">
        <template slot-scope="scope" v-if="scope.row.completionTime != null">
          <div>{{scope.row.completionTime|spliceDate2}}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="ispay" label="支付" width="80">
        <template slot-scope="scope">
          <el-tag size="medium" :type="payStateColor(scope.row.ispay)">{{scope.row.ispay|payStateToString}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column sortable prop="state" label="状态" width="80">
        <template slot-scope="scope">
          <div v-if="scope.row.state === 0" style="text-align: center;font-size: 14px">{{scope.row.state|stateToString}}</div>
          <el-tag size="medium" v-if="scope.row.state !== 0" :type="stateColor(scope.row.state)">{{scope.row.state|stateToString}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column sortable prop="created" label="创建时间" width="150">
        <template slot-scope="scope" v-if="scope.row.created != null">
          <div>{{scope.row.created|spliceDate2}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="page" @callFather="callFather" ></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
      <el-form label-width="100px" :model="editForm" ref="editForm">
        <el-form-item label="就诊医生" prop="docterId">
          <el-select v-model="editForm.doctorId" placeholder="请选择就诊医生">
            <el-option
              v-for="item in doctorList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input size="small" v-model="editForm.phone" auto-complete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="editForm.sex" label="男">男</el-radio>
          <el-radio v-model="editForm.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input size="small" v-model="editForm.age" auto-complete="off" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="editForm.state" placeholder="请选择就诊医生">
            <el-option
              v-for="item in stateList"
              :key="item.id"
              :label="item.value"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="就诊时间段" prop="appointmentPeriod">
          <span>{{checkAppointmentPeriod(editForm.appointmentPeriodId)}}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="closeDialog">取消</el-button>
        <el-button size="medium" type="primary" :loading="loading" class="title" @click="editFormBtn('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptList, deptSave, deptDelete } from '../../api/userMG'
import Pagination from '../../components/Pagination'
import {allDoctor, deletePre, getAllTimeSlot, getPreSearchList, getTimeSlotList, removePre, updatePre} from "../../api";
export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: '编辑',
      editForm: {},
      doctorList: [],
      timeSlotList: [],
      stateList: [
        { id: 0, value: '已预约'},
        { id: 1, value: '已挂号'},
        { id: 2, value: '就诊中'},
        { id: 3, value: '已完成'},
        { id: 4, value: '过号'},
        { id: -1, value: '取消'},
      ],
      // rules表单验证
      rules: {
        deptName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        deptNo: [{ required: true, message: '请输入部门代码', trigger: 'blur' }]
      },
      searchForm: {
        name: '',
        date: []
      },
      formInline: {
        draw: 1,
        length: 10,
        maxDate: '',
        minDate: '',
        orderCol: 'id',
        orderDir: 'desc',
        search: '%',
        start: 1
      },
      // 删除部门
      seletedata: {
        ids: '',
        token: localStorage.getItem('logintoken')
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      tableData: [],
      // 分页参数
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      multipleSelection: []
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    let _this = this
    let date = new Date()
    let today = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + ' 00:00:00'
    this.getdata(this.formInline)
    allDoctor()
      .then(res => {
        _this.doctorList = res.result
      })
      .catch(err => {
        console.log(err)
      })
    getAllTimeSlot()
      .then(res => {
        _this.timeSlotList = res.result
      })
      .catch(err => {
        console.log(err)
      })
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    table_Data() {
      let _this = this
      this.loading = false
      this.tableData = this.listData.slice((_this.page.currentPage-1)*_this.page.pageSize, _this.page.currentPage*_this.page.pageSize)
    },
    // 获取公司列表
    getdata(parameter) {
      this.loading = true
      let _this = this
      getPreSearchList({
        params: parameter
      })
        .then(res => {

          if (res.success === false) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.listData = res.result.data
            // 分页赋值
            this.page.total = res.result.recordsFiltered
            _this.table_Data()
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('信息加载失败，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parm) {
      this.page.currentPage = parm.currentPage
      this.page.pageSize = parm.pageSize
      this.table_Data()
    },
    set0(s) {
      return s < 10 ? '0' + s : s
    },
    // 搜索事件
    search() {
      let _this = this
      if (this.searchForm.name != null) {
        this.formInline.search = this.searchForm.name
      }
      if (this.searchForm.date != null && this.searchForm.date.length > 0) {
        let start = new Date(this.searchForm.date[0])
        let startDate = start.getFullYear() + '-' + this.set0((start.getMonth() + 1)) + '-' + this.set0(start.getDate())
        // let startTime = this.set0(start.getHours()) + ':' + this.set0(start.getMinutes()) + ':' + this.set0(start.getSeconds())
        let startTime = '00:00:00'

        let end = new Date(this.searchForm.date[1])
        let endDate = end.getFullYear() + '-' + this.set0((end.getMonth() + 1)) + '-' + this.set0(end.getDate())
        // let endTime = this.set0(end.getHours()) + ':' + this.set0(end.getMinutes()) + ':' + this.set0(end.getSeconds())
        let endTime = '23:59:59'

        this.formInline.minDate = startDate + " " + startTime
        this.formInline.maxDate = endDate + " " + endTime
        if (this.formInline.minDate === 'NaN-NaN-NaN 00:00:00' && this.formInline.maxDate === 'NaN-NaN-NaN 23:59:59') {
          _this.formInline.minDate = ''
          _this.formInline.maxDate = ''
        }
      }
      if (this.searchForm.name === null && this.searchForm.date !== null){
        this.formInline.search = '%'
      }
      if (this.searchForm.name !== null && this.searchForm.date === null){
        this.formInline.minDate = ''
        this.formInline.maxDate = ''
      }
      this.getdata(_this.formInline)
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true
      this.editForm = row
    },
    // 编辑、增加页面保存方法
    editFormBtn() {
      let _this = this
      updatePre({
        'id': _this.editForm.id,
        'doctorId': _this.editForm.doctorId,
        'name': _this.editForm.name,
        'phone': _this.editForm.phone,
        'sex': _this.editForm.sex,
        'age': _this.editForm.age,
        'state': _this.editForm.state
      })
        .then(res => {
          _this.editFormVisible = false
          _this.loading = false
          if (res.success) {
            this.getdata(this.formInline)
            this.$message({
              type: 'success',
              message: '更新成功！'
            })
          } else {
            this.$message({
              type: 'info',
              message: '更新失败'
            })
          }
        })
        .catch(err => {
          _this.editFormVisible = false
          _this.loading = false
          _this.$message.error('更新失败，请稍后再试！')
        })
    },
    // 删除订单
    deleteUser(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let params = new URLSearchParams()
          params.append('preIds', [row.id])
          removePre(params)
            .then(res => {
              if (res.success) {
                this.$message({
                  type: 'success',
                  message: '记录已删除!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('记录删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    deletePres: function () {
      let _this = this
      this.$confirm('确定要批量删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let array = []
          for (let i = 0; i < _this.multipleSelection.length; i++) {
            array.push(_this.multipleSelection[i].id)
          }
          let params = new URLSearchParams()
          params.append('preIds', array)
          removePre(params)
            .then(res => {
              if (res.success) {
                _this.multipleSelection = []
                this.$message({
                  type: 'success',
                  message: '记录已删除!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('记录删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    checkAppointmentPeriod: function (appointmentPeriodId) {
      if (appointmentPeriodId === 99) {
        return '加号'
      }
      for (let i = 0; i < this.timeSlotList.length; i++) {
        if (this.timeSlotList[i].id === appointmentPeriodId) {
          return this.timeSlotList[i].timeSlot
        }
      }
    },
    downloadFile: function () {
      window.location.href="https://mp.wwtsz.com:8812/manager/preInfo/out";
    },
    downloadFiles: function () {
      let _this = this
      let array = []
      for (let i = 0; i < _this.multipleSelection.length; i++) {
        array.push(_this.multipleSelection[i].id)
      }
      window.location.href="https://mp.wwtsz.com:8812/manager/batch/preInfo/out?preIds=" + array;
    },
    getRowsKeys(row) {
      return row.staffTypeId
    },
    stateColor: function (state) {
      if (state === 1) {
        return
      }
      if (state === 2) {
        return 'warning'
      }
      if (state === 3) {
        return 'success'
      }
      if (state === 4) {
        return 'info'
      }
      if (state === -1) {
        return 'danger'
      }
    },
    payStateColor: function (state) {
      if (state === -1) {
        return 'info'
      }
      if (state === 0) {
        return 'warning'
      }
      if (state === 1) {
        return 'success'
      }
    }
  },
  filters: {
    stateToString: function (state) {
      switch (state) {
        case 0: return "已预约";
        case 1: return "已挂号";
        case 2: return "就诊中";
        case 3: return "已完成";
        case 4: return "过号";
        case -1: return "取消";
        default: return "/"
      }
    },
    payStateToString: function (state) {
      switch (state) {
        case -1: return "已退款"
        case 0: return "未支付"
        case 1: return "已支付"
      }
    },
    spliceDate: function (value) {
      return value.substr(0,10)
    },
    spliceDate2: function (value) {
      return value.substr(0,16)
    },
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>


